import json
from decimal import Decimal
from django.utils import timezone

from django.shortcuts import render
from django_redis import get_redis_connection
from django.http import JsonResponse, HttpResponseBadRequest
from apps.goods.models import SKU
from apps.orders.models import OrderInfo,OrderGoods
from apps.users.models import Address
from utils.views import LoginRequiredJSONMixin
from django.views import View
# Create your views here.


class OrderSettlementView(LoginRequiredJSONMixin, View):
    def get(self, request):
        user = request.user
        # 查询当前用户的所有地址信息
        addresses = Address.objects.filter(user=user,is_deleted=False)
        addresses_list = []
        for address in addresses:
            addresses_list.append({
                'id': address.id,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'place': address.place,
                'receiver': address.receiver,
                'mobile': address.mobile
            })
        # 从Redis购物车中查询出被勾选的商品信息
        redis_cli = get_redis_connection('carts')
        pl = redis_cli.pipeline()
        pl.hgetall('carts_%s' % user.id)
        pl.smembers('selected_%s' % user.id)
        result = pl.execute()
        sku_id_counts = result[0]
        selected_ids = result[1]

        selected_carts = {}
        for sku_id in selected_ids:
            selected_carts[int(sku_id)] = int(sku_id_counts[sku_id])

        sku_list = []
        for sku_id,count in selected_carts.items():
            sku = SKU.objects.get(pk=sku_id)
            sku_list.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url':sku.default_image.url,
                'count': count,
                'price':sku.price
            })
        # 运费
        freight = Decimal('10.00')
        # 渲染界面
        context = {
            'addresses': addresses_list,
            'skus': sku_list,
            'freight': freight,
        }
        return JsonResponse({'code':0,'errmsg':'ok', 'context':context})


class OrderCommitView(LoginRequiredJSONMixin, View):
    """提交订单"""
    def post(self, request):
        """保存订单信息和订单商品信息"""
        user = request.user
        data = json.loads(request.body.decode())
        address_id = data.get('address_id')
        pay_method = data.get('pay_method')

        if not all([address_id, pay_method]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})

        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数不正确'})

        if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'], OrderInfo.PAY_METHODS_ENUM['ALIPAY']]:
            return JsonResponse({'code': 400, 'errmsg': '参数pay_method错误'})
        # 生成order_id主键：年月日时分秒+用户编号
        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)

        if pay_method == OrderInfo.PAY_METHODS_ENUM['CASH']:
            pay_status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        else:
            pay_status = OrderInfo.ORDER_STATUS_ENUM['UNPAID']

        total_count=0
        total_amount = Decimal('0')
        freight=Decimal('10.00')
        # 保存订单基本信息 OrderInfo（一）
        orderinfo = OrderInfo.objects.create(
            order_id=order_id,
            user=user,
            address=address,
            total_count=0,
            total_amount=Decimal('0'),
            freight=Decimal('10.00'),
            pay_method=pay_method,
            status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY'] else
            OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        )
        redis_cli = get_redis_connection('carts')
        sku_id_counts = redis_cli.hgetall('carts_%s' % user.id)
        selected_ids = redis_cli.smembers('selected_%s' % user.id)
        carts = {}
        for sku_id in selected_ids:
            carts[int(sku_id)] = int(sku_id_counts[sku_id])
        # 遍历
        for sku_id,count in carts.items():
            # 查询SKU信息
            sku = SKU.objects.get(id=sku_id)
            # 判断SKU库存

            if sku.stock < count:
                return JsonResponse({'code': 400, 'errmsg': '库存不足'})
            # SKU减少库存，增加销量
            sku.stock -= count
            sku.sales += count
            sku.save()

            orderinfo.total_count+=count
            orderinfo.total_amount+=(count*sku.price)

            # 保存订单商品信息 OrderGoods（多）
            OrderGoods.objects.create(
                order=orderinfo,
                sku=sku,
                count=count,
                price=sku.price,
            )
        #     # 保存商品订单中总价和总数量
            orderinfo.total_count += count
            orderinfo.total_amount += (count * sku.price)
        #
        # # 添加邮费和保存订单信息
        orderinfo.total_amount += orderinfo.freight
        orderinfo.save()
        #
        # # 清除购物车中已结算的商品
        pl = redis_cli.pipeline()
        pl.hdel('carts_%s' % user.id, *selected_ids)
        pl.srem('selected_%s' % user.id, *selected_ids)
        pl.execute()
        #
        orderinfo.save()
        # 响应提交订单结果
        return JsonResponse({'code': 0, 'errmsg': '下单成功', 'order_id': order_id})
